# knowledge/__init__.py

"""
企业知识库管理系统
支持多层级文件夹结构、增量更新和智能检索
"""

__version__ = "1.0.0"
__author__ = "Enterprise Knowledge Base Team"

# 配置日志
import logging
import os
from logging.handlers import TimedRotatingFileHandler

def setup_logging(verbose=False, log_dir=None):
    """设置日志配置 - 增强版本，支持按级别分离日志文件"""
    import logging
    
    # 清除所有现有的处理器和配置
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)
    
    # 设置根日志器为DEBUG级别，确保所有日志都能被捕获
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    
    # 创建格式化器
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # 控制台处理器 - 始终显示INFO及以上级别
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)  # 控制台只显示INFO及以上
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    
    # 文件处理器 - 始终记录所有级别到文件
    if log_dir is None:
        # 默认日志目录：knowledge/logs/
        current_dir = os.path.dirname(os.path.abspath(__file__))
        knowledge_dir = os.path.dirname(current_dir)
        log_dir = os.path.join(knowledge_dir, "logs")
    
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # DEBUG级别日志文件 - 记录DEBUG及以上级别，按天轮转，保留30天
    debug_file_handler = TimedRotatingFileHandler(
        filename=os.path.join(log_dir, 'debug.log'),
        when='midnight',  # 每天午夜轮转
        interval=1,       # 每天一个文件
        backupCount=30,   # 保留30天
        encoding='utf-8'
    )
    debug_file_handler.setLevel(logging.DEBUG)  # 记录DEBUG及以上
    debug_file_handler.setFormatter(formatter)
    # 为DEBUG处理器添加过滤器，排除第三方库的DEBUG日志
    debug_file_handler.addFilter(ThirdPartyDebugFilter())
    root_logger.addHandler(debug_file_handler)
    
    # INFO级别日志文件 - 记录INFO及以上级别，按天轮转，保留30天
    info_file_handler = TimedRotatingFileHandler(
        filename=os.path.join(log_dir, 'info.log'),
        when='midnight',  # 每天午夜轮转
        interval=1,       # 每天一个文件
        backupCount=30,   # 保留30天
        encoding='utf-8'
    )
    info_file_handler.setLevel(logging.INFO)   # 记录INFO及以上
    info_file_handler.setFormatter(formatter)
    root_logger.addHandler(info_file_handler)
    
    # 设置第三方库的日志级别，避免干扰
    third_party_loggers = [
        'dashscope', 'chromadb', 'httpx', 'httpcore', 'urllib3',
        'openai', 'backoff', 'llama_index', 'fsspec', 'filelock',
        'asyncio', 'charset_normalizer', 'httpcore.connection',
        'httpcore.http11', 'hpack'
    ]
    for logger_name in third_party_loggers:
        lib_logger = logging.getLogger(logger_name)
        # 第三方库设置为WARNING级别，减少噪音
        lib_logger.setLevel(logging.WARNING)
        # 允许传播，这样文件处理器仍然会记录WARNING和ERROR
        lib_logger.propagate = True
    

class ThirdPartyDebugFilter(logging.Filter):
    """过滤器：阻止第三方库的DEBUG日志进入DEBUG日志文件"""
    
    def filter(self, record):
        # 如果是DEBUG级别且来自第三方库，则过滤掉
        if record.levelno == logging.DEBUG:
            third_party_names = [
                'dashscope', 'chromadb', 'httpx', 'httpcore', 'urllib3',
                'openai', 'backoff', 'llama_index', 'fsspec', 'filelock',
                'asyncio', 'charset_normalizer', 'httpcore.connection',
                'httpcore.http11', 'hpack'
            ]
            for name in third_party_names:
                if record.name.startswith(name):
                    return False
        return True

# 提供懒加载功能
def __getattr__(name):
    if name == "KnowledgeBaseApplication":
        from knowledge.core.kb_application import KnowledgeBaseApplication
        return KnowledgeBaseApplication
    elif name == "KnowledgeBaseConfig":
        from knowledge.base.kb_base import KnowledgeBaseConfig
        return KnowledgeBaseConfig
    elif name == "KBDocumentProcessor":
        from knowledge.processors.kb_document_processor import KBDocumentProcessor
        return KBDocumentProcessor
    elif name == "KBVectorStoreManager":
        from knowledge.vector.kb_vector_store_manager import KBVectorStoreManager
        return KBVectorStoreManager
    elif name == "KBQueryEngine":
        from knowledge.query.kb_query_engine import KBQueryEngine
        return KBQueryEngine
    else:
        raise AttributeError(f"模块 knowledge 没有属性 {name}")